from flask import Blueprint, render_template, request
from flask_login import current_user, login_required

from extensions import db
from qingdeng.orms import ArticleORM, CommentORM, UserORM

article_bp = Blueprint("article", __name__)


@article_bp.route("/article/<int:article_id>")
def article_view(article_id):
    article: ArticleORM = ArticleORM.query.get(article_id)
    hot_article_list = (
        ArticleORM.query.order_by(ArticleORM.clicks.desc()).limit(10).all()
    )

    # 文章是否已经被收藏过了
    is_collect = False
    user: UserORM = current_user
    if user.is_active:
        is_collect = True if (article in user.collection_article_list) else False

    author: UserORM = article.user  # 文章没有作者 就是 None
    # 文章有作者才能判断是否关注
    # 如果当前用户存在于文章作者的关注列表里面
    is_followed = False
    if author:  # 文章有作者才能判断用户是不是作者的粉丝
        is_followed = True if user in author.followers else False
    # 显示文章的评论
    comment_list = article.comment_list  # 可以对评论进行排序

    return render_template(
        "bbs/article.html",
        article=article,
        hot_article_list=hot_article_list,
        author=author,
        is_collect=is_collect,
        comment_list=comment_list,
        is_followed=is_followed,
    )


# login_required  # 收藏文章打上一个登录的装饰器
@article_bp.route("/article/article_collect", methods=["POST"])
def article_collect_view():
    user: UserORM = current_user  # 已经登录的用户 匿名用户

    if not user.is_active:
        return {"status": "fail", "message": "请先登录", "code": 4101}
    article_id = request.json.get("article_id")
    action = request.json.get("action")
    article: ArticleORM = ArticleORM.query.get(int(article_id))
    if not article or action not in ["collect", "cancel_collect"]:
        return {"status": "fail", "message": "请求参数有误", "code": 4102}
    # 前后端都需要完善
    if action == "collect":
        user.collection_article_list.append(article)
        msg = "收藏成功"
    else:
        user.collection_article_list.remove(article)
        msg = "取消收藏成功"
    db.session.commit()
    return {"status": "success", "message": msg, "code": 0}


@article_bp.route("/article/article_comment", methods=["POST"])
@login_required
def article_comment_view():
    article_id = request.json.get("article_id")
    content = request.json.get("comment")
    parent_id = request.json.get("parent_id")
    if not content:
        return {"status": "fail", "message": "没有评论内容"}, 401

    # 评论文章
    # 1. 拿到文章对象
    article = ArticleORM.query.get(int(article_id))
    # 2. 拿到评论对象
    comment: CommentORM = CommentORM()
    comment.user_id = current_user.id
    comment.content = content

    # 如果有父级评论
    if parent_id:
        comment.parent_id = int(parent_id)

    # 3. 评论与文字通过外键关联
    # comment.article_id = article_id
    article.comment_list.append(comment)
    db.session.add(article)
    db.session.commit()

    return {"status": "success", "message": "评论文章成功"}


"""
    评论的显示方式
    1. 返回文章的时候把评论渲染到页面(jinja2静态渲染)
    2. 返回文章之后,在前端动态请求通过前端渲染的方式实现
        2.1 实现的时候麻烦一点
        2.2 可以实现对评论的分页处理
"""


@article_bp.route("/article/comment_like", methods=["POST"])
@login_required
def comment_like_view():
    action = request.json.get("action")
    comment_id = request.json.get("comment_id")
    # 1. 获取评论对象
    comment: CommentORM = CommentORM.query.get(int(comment_id))
    # 2. 获取点赞对象
    user: UserORM = current_user
    msg = ""
    if action == "add":
        user.comment_like_list.append(comment)
        msg = "点赞评论成功"
    elif action == "remove":
        user.comment_like_list.remove(comment)
        msg = "取消点赞评论成功"
    db.session.commit()

    return {
        "status": "success",
        "message": msg,
    }


@article_bp.route("/article/followed_user", methods=["POST"])
@login_required
def follow_user():
    author_id = request.json.get("user_id")
    action = request.json.get("action")

    # 实现关注的逻辑
    author: UserORM = UserORM.query.get(int(author_id))
    user: UserORM = current_user
    msg = ""
    if action == "follow":
        user.followed.append(author)
        msg = "关注用户成功"
    elif action == "unfollow":
        user.followed.remove(author)
        msg = "取消关注用户成功"
    db.session.commit()
    return {"status": "success", "message": msg}
